package gitobject;



import JitUtils.FileHash;
import sha1.SHA1;

import zlib.ZLibUtils;
import fileoperation.FileReader;

import java.io.*;
import java.lang.reflect.Array;
import java.security.MessageDigest;
import java.util.*;

/**
 * tree的value中需要包含其中文件与文件夹的名称与hash值，tree的key值由tree的value得到
 */

public class Tree extends GitObject implements Serializable{
    public static long serialVersionUID = 4754631534532L;
//    protected ArrayList<GitObject> treeList;	//GitObjects in tree
    public static ArrayList<String> blobList = null;

//    public ArrayList<GitObject> getTreeList(){
//        return treeList;
//    }

    public Tree(){}
    
    /**
     * Constructor
     * @param file
     * @throws Exception
     */
    public Tree(File file) throws Exception {

//        this.treeList = new ArrayList<>();
        this.fmt = "tree";
        this.mode = "040000";
        this.value = "";
        genKey(file);
//        compressWrite();
    }

    /**
     * Deserialize a tree object with treeId and its path.
     * @param Id
     * @param Id
     * @throws IOException
     */
    public static Tree deserialize(String Id) throws IOException {
        ObjectInputStream ois = null;
        Tree tree = null;
        try{
            ois = new ObjectInputStream(new FileInputStream(Id));
            tree = (Tree) ois.readObject();
            return tree;
        }catch (Exception e){
            e.printStackTrace();
        }finally{
            if(ois != null){
                try {
                    ois.close();;
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
        return tree;
    }


    /**
     * Sort the files in a certain order. You should consider whether it's a file or a directory.
     * @param fs
     * @return List
     */
    public List sortFile(File[] fs){
        List fileList = Arrays.asList(fs);
        Collections.sort(fileList, new Comparator<File>() {
            @Override //表示重写方法
            public int compare(File o1, File o2) {
                return (o1.getAbsolutePath()).compareTo(o2.getAbsolutePath());
            }
        });
        return fileList;
    }

    /**
     * Generate the key of a tree object.
     * @param dir
     * @return String
     * @throws Exception
     */
    public String genKey(File dir) throws Exception{
        /* Todo: Add your code here. */
        this.key = FileHash.hashOfDic(dir).getId();
        return key;
    }

    @Override
    public String toString(){
        return "040000 tree " + key;
    }

}
